<?php

namespace app\api\controller;

use app\api\model\Category;
use app\common\controller\Api;
use app\api\model\Training as TrainingModel;

class Training extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function add()
    {
        $param = $this->request->param();
        $user= $this->auth;
        $TrainingModel = new TrainingModel();
        $param['user_id']=$user->id;
        $param['createtime']=time();
        $param['status']=2;
        $TrainingModel->save($param);
        $this->success('');
    }
    public function myList()
    {
        $param = $this->request->param();
        $user= $this->auth;
        $TrainingModel = new TrainingModel();
        $where['user_id']=$user->id;
        if(!empty($param['status'])){
            $where['status']=$param['status'];
        }
        if(!empty($param['keyword'])){
            $where['title']=['like','%'.$param['keyword']."%"];
        }
        $list=$TrainingModel->where($where)->paginate(10);
        $this->success('',$list);

    }
    public function info()
    {
        $param = $this->request->param();
        $TrainingModel = new TrainingModel();
        $where['id']=$param['id'];
        $find=$TrainingModel->where($where)->find();
        $this->success('',$find);
    }
    public function edit()
    {
        $param = $this->request->param();
        $user= $this->auth;
        $TrainingModel = new TrainingModel();
        $param['user_id']=$user->id;
        $param['status']=2;
        $where['id']=$param['id'];
        $TrainingModel->save($param,$where);
        $this->success('');
    }
    public function delete()
    {
        $param = $this->request->param();
        $TrainingModel = new TrainingModel();
        $where['id']=$param['id'];
        $TrainingModel->where($where)->delete();
        $this->success('');
    }
    public function List()
    {
        $param = $this->request->param();
        $TrainingModel = new TrainingModel();
        $Category = new Category();
        $where['status']=1;
        if(!empty($param['category_id'])){
            $where['category_id']=$param['category_id'];
        }
        if(!empty($param['keyword'])){
            $where['title']=['like','%'.$param['keyword']."%"];
        }
        $list=$TrainingModel->where($where)->paginate(10)->each(function ($item,$key)use($Category){
            $item['category_name']=$Category->where('id',$item['category_id'])->value('name');
            return $item;
        });
        $this->success('',$list);
    }
    public function Details()
    {
        $param = $this->request->param();
        $user= $this->auth;
        $TrainingModel = new TrainingModel();
        $where['id']=$param['id'];
        $find=$TrainingModel->where($where)->find();


        $score=$this->score_change($user->id,$find['score'],'1',$find['title']."获得积分",1);
        $this->score_day_log($user->id,$score,$find['id'],4);

        $this->success('',$find);
    }
}
